<template>
    <div class="coverage-distribution">
        <div class="header">
            <div class="flex title">
                <h1>城市媒体覆盖分布</h1>
                <div>
                    <span :class="isCheckMedia && 'checked'" @click="changeMediaCheckState">电梯媒体</span>
                    <span :class="!isCheckMedia && 'checked'" @click="changeMediaCheckState">门禁</span>
                </div>
            </div>
        </div>
        <div v-if="isCheckMedia && !hasNoData">
            <div class="flex total">
                <template v-for="item in tableData" :key="item.type">
                    <div
                        v-if="item.type !== 5" class="total-item" :class="(currentMediaType === item.type) && 'checked'"
                        @click="changeMediaType(item)"
                    >
                        <div class="key">
                            {{ item.name }}
                        </div>
                        <div class="value" :class="isAndroid && 'android'">
                            {{ $numberWithCommas(item.total) }}
                        </div>
                    </div>
                </template>
            </div>
            <div ref="barChart" :style="{ width: '100%', height: '90px' }" class="chart"></div>
            <div class="market-link">
                <a class="desc" @click="descVisible = true">指标说明
                    <img src="@/assets/img/cph-tips.png" alt=""></a>
                <a @click="toPage">查看市场份额</a>
            </div>
            <div class="table">
                <my-table
                    ref="tableRef" :key="keyNum" :title-array="headData" :config="{
                        isColHeadAverage: false,
                        isWeightData: true,
                        isWeightHeader: true
                    }" :data="tdData" :focus-index="currentMediaType"
                ></my-table>
            </div>
        </div>
        <div v-if="isCheckMedia && hasNoData" class="empty">
            <div>
                <img src="@/assets/img/empty.png" alt="">
                <p>暂无数据</p>
            </div>
        </div>
        <div v-if="!isCheckMedia" class="empty">
            <img src="@/assets/img/expect.png" alt="">
        </div>
    </div>
    <DescPop :show="descVisible" @close="() => descVisible = false" />
</template>

<script lang="ts" setup>
import { ref, PropType, watch } from 'vue';
import * as echarts from 'echarts';
import type { EChartsType } from 'echarts';
import { nextTick } from 'vue';
import MyTable from '@/components/Table/index.vue';
import { CoverNumberItemModel } from '../home.module';
import { useRouter } from 'vue-router';
import DescPop from './descPop.vue';

const props = defineProps({
    tableData: {
        type: Array as PropType<CoverNumberItemModel[]>,
        default: () => []
    },
    hasNoData: {
        type: Boolean,
        default: false,
    },
    scene: {
        type: Number,
        default: 1
    },
    city: {
        type: String,
        default: ''
    }
});

const keyNum = ref(0);
const barChart = ref(null);
const isCheckMedia = ref(true);
const currentMediaType = ref(2);
const isAndroid = ref(false);
const currentChartIndex = ref();
const tableRef = ref();
const tdData = ref<{ col1: string, col2: number, col3: number, col4: number }[]>([]);
const headData = ref<string[]>(['资源总览', '智能屏', 'LCD', '海报']);
const descVisible = ref(false);
let myChart: EChartsType | null = null;

const router = useRouter();
const toPage = async () => {
    await router.push({ path: '/products/market_share_details', query: { scene: props.scene,cityCode: props.city } });
};

// 处理表数据
const handleTableData = () => {
    keyNum.value++;
    tdData.value = [];
    props.tableData?.forEach((item: CoverNumberItemModel) => {
        tdData.value.push({
            col1: item.name,
            col2: item.screen,
            col3: item.lcd,
            col4: item.poster
        });
    });
};

const handleData = () => {
    const current = props.tableData?.find(item => item.type === currentMediaType.value);
    const data = [current?.screen || 0, current?.lcd || 0, current?.poster || 0];
    const max = Math.max(...data);
    return {
        data,
        max
    };
};

const setOption = () => {
    const { data, max } = handleData();
    const option1 = {
        tooltip: {
            show: true,
            // position: 'inside',
            // confine: true
        },
        grid: {
            left: max < 4 ? 30 + 20 : Number(max.toString().length + 1) * 7.5 + 20,
            top: 8,
            bottom: 20,
            right: 0,
        },
        xAxis: [{
            type: 'category',
            data: ['智能屏', 'LCD', '海报'],
            axisTick: {
                show: false,
            },
            axisLine: {
                interval: '50',
                lineStyle: {
                    color: ['#eeeeee'],
                    width: 1,
                    opacity: 0.5
                }
            },
            axisLabel: {
                color: '#848484',
                fontSize: 11
            },
        }, {
            type: 'category',
            data: ['智能屏', 'LCD', '海报'],
            show: false
        }],
        axisTick: {
            show: false,
        },
        color: ['#F7135E'],
        yAxis: {
            type: 'value',
            min: 0,
            // max: Math.ceil(max+max*0.2),
            splitNumber: max >= 4 && 3,
            axisLabel: {
                color: '#848484',
                fontSize: 10,
            },
            splitLine: {
                lineStyle: {
                    color: ['#eeeeee'],
                    width: 1,
                    type: 'dashed',
                    opacity: 1
                }
            },
            axisTick: {
                inside: true
            },
            scale: true
        },
        series: [{
            data: data,
            barWidth: 25,
            type: 'bar'
        },
        {
            xAxisIndex: 1,
            silent: true,
            select: {
                disabled: true
            },
            itemStyle: {
                color: ({ dataIndex }: { dataIndex: number }) => {
                    if (dataIndex === currentChartIndex.value) {
                        return 'rgba(180, 180, 180, 0.2)';
                    }
                    return 'rgba(0,0,0,0)';
                }
            },
            data: data.map((item, index) => {
                return {
                    value: data[index] + data[index] * 0.2,
                };
            }),
            barWidth: 50,
            type: 'bar'
        }
        ]
    };
    return option1;
};

const initChart = () => {
    const dom = barChart.value;
    const { data, max } = handleData();
    const index = data?.findIndex(item => item === max) || 0;
    currentChartIndex.value = index;
    if (dom) {
        if (myChart) {
            myChart.dispose();
        }

        myChart = echarts.init(dom);
        myChart.setOption(
            setOption()
        );
        window.onresize = function () {
            if (myChart) {
                myChart.resize();
            }

        };
    }

    if (myChart) {
        myChart.on('click', function (param) {
            currentChartIndex.value = param.dataIndex;
            myChart?.setOption(setOption());
        });
        // myChart.dispatchAction({
        //     type: 'showTip',
        //     seriesIndex: 0, // 针对series下第几个数据
        //     dataIndex: index, // 第几个数据
        //     position: [130,0]
        // });
    }
};

const changeMediaCheckState = async () => {
    isCheckMedia.value = !isCheckMedia.value;
    if (isCheckMedia.value) {
        await nextTick(() => {
            initChart();
        });
    }
};

const changeMediaType = async (item: CoverNumberItemModel) => {
    currentMediaType.value = item.type;
    await nextTick(() => {
        initChart();
    });
};

function getPlatForm() {
    const u = navigator.userAgent;
    isAndroid.value = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
}

const initMediaType = ()=>{
    currentMediaType.value = 2;
};

watch(
    () => props.tableData,
    async (newVal) => {
        if (newVal.length) {
            await nextTick(() => {
                initChart();
                handleTableData();
                getPlatForm();
            });
        }
    }
);

defineExpose({
    initMediaType
});
</script>

<style lang="scss" scoped>
@import "@/styles/variables";

.coverage-distribution {
    background: #ffffff;
    border-radius: 10px;
    padding: 16px 12px;
    margin-bottom: 12px;

    .flex {
        display: flex;
    }

    .header {
        .title {
            justify-content: space-between;
            height: 22px;
            align-items: center;

            h1 {
                font-weight: 600;
                font-size: 16px;
                color: #333333;
            }

            div {
                padding: 2px;
                background: #fafafa;
                border-radius: 4px;

                span {
                    display: inline-block;
                    width: 84px;
                    height: 26px;
                    line-height: 26px;
                    font-weight: 400;
                    font-size: 13px;
                    color: #848484;
                    letter-spacing: 0;
                    text-align: center;
                }

                .checked {
                    background: #ffffff;
                    color: #333333;
                    box-shadow: 0 1px 2px 0 #0000000f;
                    border-radius: 4px;
                }
            }
        }
    }

    .total {
        margin-top: 20px;
        justify-content: space-between;

        .total-item {
            // flex: 1;
            text-align: center;
            position: relative;
            // height: 47px;

            .key {
                font-weight: 400;
                font-size: 12px;
                height: 20px;
                line-height: 20px;
                color: #848484;
                letter-spacing: 0;
            }

            .value {
                margin-top: 2px;
                height: 19px;
                line-height: 19px;
                font-family: $spec_font;
                font-size: 16px;
                color: #333333;
                letter-spacing: 0;
            }

            .android {
                font-family: $spec_font;
            }
        }

        .checked::after {
            content: "";
            display: block;
            width: 20px;
            height: 4px;
            background: #e60044;
            border-radius: 2px;
            margin: 3px auto 0;
        }

        .checked .value {
            color: #e60044;
        }
    }

    .market-link {
        display: flex;
        justify-content: space-between;
        margin-top: 12px;

        a {
            height: 17px;
            line-height: 17px;
            font-weight: 400;
            font-size: 12px;
            color: #397ff8;
        }

        a.desc {
            font-family: PingFangSC-Regular, sans-serif;
            font-weight: 400;
            font-size: 12px;
            color: #848484;
            display: flex;
            align-items: center;

            img {
                width: 14px;
                height: 14px;
                margin-left: 4px;
            }
        }
    }

    .chart {
        margin-top: 8px;
    }

    .table {
        margin-top: 16px;
    }

    .empty {
        display: flex;
        justify-content: center;
        min-height: 200px;
        align-items: center;

        img {
            width: 189px;
            height: 129px;
        }

        p {
            font-weight: 400;
            font-size: 14px;
            color: #b5b5b5;
            margin-top: 12px;
            text-align: center;
            height: 20px;
        }
    }
}
</style>
